package com.wsoft.bpm.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wsoft.bpm.entity.ActProcessMappingEntity;
import com.wsoft.bpm.query.mapping.ActProcessMappingQuery;
import com.wsoft.bpm.service.IActProcessMappingService;
import com.wsoft.core.exception.Asserts;
import com.wsoft.response.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 流程模版与业务表映射关系
 *
 * @author zhonglj
 * @since 2024年10月11日 15:01:41
 */
@RestController
@Tag(name = "流程模版与业务表映射")
@RequestMapping("/bpm/mapping")
public class ActProcessMappingController {

    @Resource
    private IActProcessMappingService actProcessMappingService;

    @Operation(summary = "新增", description = "新增流程模版与业务表映射关系")
    @PostMapping("/insert")
    public ResponseResult insert(@RequestBody @Validated ActProcessMappingQuery req) {
        ActProcessMappingEntity convert = Convert.convert(ActProcessMappingEntity.class, req);
        checkParams(req);
        actProcessMappingService.save(convert);
        return ResponseResult.success("[sys.msg.success]");
    }

    /**
     * 检查参数
     *
     * @param req
     * @return void
     * @author zhonglj
     * @date 2024-10-12 10:00
     **/
    private void checkParams(ActProcessMappingQuery req) {
        LambdaQueryWrapper<ActProcessMappingEntity> wrapper = Wrappers.lambdaQuery(ActProcessMappingEntity.class);
        // 确保processKey
        if (actProcessMappingService.count(wrapper
                .eq(ActProcessMappingEntity::getProcessKey, req.getProcessKey())
        ) > 0) {
            Asserts.fail("[bpm.mapping.error.insert.processKey.duplicate]");
        }

        wrapper.clear();
        if (actProcessMappingService.count(wrapper
                .eq(ActProcessMappingEntity::getTableName, req.getTableName())
        ) > 0) {
            Asserts.fail("[bpm.mapping.error.insert.tableName.duplicate]");
        }
    }
}
